| Conditions | 15 |
| Total Lines | 96 |
| Code Lines | 76 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like singleResourceHook.ts ➔ useResource often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | import { Reducer, useCallback, useEffect, useReducer, useRef } from "react"; |
||
| 123 | |||
| 124 | export function useResource<T>( |
||
| 125 | endpoint: string, |
||
| 126 | initialValue: T, |
||
| 127 | overrides?: { |
||
| 128 | parseResponse?: (response: Json) => T; // Defaults to the identity function. |
||
| 129 | skipInitialRefresh?: boolean; // Defaults to false. Override if you want to keep the initialValue until refresh is called manually. |
||
| 130 | handleError?: (error: Error | FetchError) => void; // In addition to using the error returned by the hook, you may provide a callback called on every new error. |
||
| 131 | }, |
||
| 132 | ): UseResourceReturnType<T> { |
||
| 133 | const parseResponse = overrides?.parseResponse ?? identity; |
||
| 134 | const doInitialRefresh = overrides?.skipInitialRefresh !== true; |
||
| 135 | const handleError = overrides?.handleError ?? doNothing; |
||
| 136 | const isSubscribed = useRef(true); |
||
| 137 | |||
| 138 | const [state, dispatch] = useReducer< |
||
| 139 | Reducer<ResourceState<T>, AsyncAction<T>> |
||
| 140 | >(reducer, initialState(initialValue, doInitialRefresh)); |
||
| 141 | |||
| 142 | const refresh = useCallback(async (): Promise<T> => { |
||
| 143 | dispatch({ type: ActionTypes.GetStart }); |
||
| 144 | let json: Json; |
||
| 145 | try { |
||
| 146 | json = await getRequest(endpoint).then(processJsonResponse); |
||
| 147 | } catch (error) { |
||
| 148 | if (isSubscribed.current) { |
||
| 149 | dispatch({ |
||
| 150 | type: ActionTypes.GetReject, |
||
| 151 | payload: error, |
||
| 152 | }); |
||
| 153 | handleError(error); |
||
| 154 | } |
||
| 155 | throw error; |
||
| 156 | } |
||
| 157 | const responseValue = parseResponse(json) as T; |
||
| 158 | if (isSubscribed.current) { |
||
| 159 | dispatch({ |
||
| 160 | type: ActionTypes.GetFulfill, |
||
| 161 | payload: responseValue, |
||
| 162 | }); |
||
| 163 | } |
||
| 164 | return responseValue; |
||
| 165 | }, [endpoint, parseResponse, handleError]); |
||
| 166 | |||
| 167 | const update = useCallback( |
||
| 168 | async (newValue): Promise<T> => { |
||
| 169 | dispatch({ type: ActionTypes.UpdateStart, meta: { item: newValue } }); |
||
| 170 | let json: Json; |
||
| 171 | try { |
||
| 172 | json = await putRequest(endpoint, newValue).then(processJsonResponse); |
||
| 173 | } catch (error) { |
||
| 174 | if (isSubscribed.current) { |
||
| 175 | dispatch({ |
||
| 176 | type: ActionTypes.UpdateReject, |
||
| 177 | payload: error, |
||
| 178 | meta: { item: newValue }, |
||
| 179 | }); |
||
| 180 | handleError(error); |
||
| 181 | } |
||
| 182 | throw error; |
||
| 183 | } |
||
| 184 | const responseValue = parseResponse(json) as T; |
||
| 185 | if (isSubscribed.current) { |
||
| 186 | dispatch({ |
||
| 187 | type: ActionTypes.UpdateFulfill, |
||
| 188 | payload: responseValue, |
||
| 189 | meta: { item: newValue }, |
||
| 190 | }); |
||
| 191 | } |
||
| 192 | return responseValue; |
||
| 193 | }, |
||
| 194 | [endpoint, parseResponse, handleError], |
||
| 195 | ); |
||
| 196 | |||
| 197 | // Despite the usual guidelines, this should only be reconsidered if endpoint changes. |
||
| 198 | // Changing doInitialRefresh after the first run (or the refresh function) should not cause this to rerun. |
||
| 199 | useEffect(() => { |
||
| 200 | if (doInitialRefresh) { |
||
| 201 | refresh().catch(doNothing); |
||
| 202 | } |
||
| 203 | |||
| 204 | // Unsubscribe from promises when this hook is unmounted. |
||
| 205 | return (): void => { |
||
| 206 | isSubscribed.current = false; |
||
| 207 | }; |
||
| 208 | |||
| 209 | // eslint-disable-next-line react-hooks/exhaustive-deps |
||
| 210 | }, [endpoint]); |
||
| 211 | |||
| 212 | return { |
||
| 213 | value: state.value, |
||
| 214 | status: state.status, |
||
| 215 | error: state.error, |
||
| 216 | initialRefreshFinished: state.initialRefreshFinished, |
||
| 217 | update, |
||
| 218 | refresh, |
||
| 219 | }; |
||
| 223 |